package controllers.accounts;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import framework.base.BaseController;
import framework.base.PagerRS;
import framework.utils.CollectionUtil;
import framework.utils.DicUtil;
import framework.utils.SecurityUtil;
import framework.utils.StringUtil;
import models.accounts.Account;
import models.accounts.AccountConstant;
import models.accounts.vo.AccountQuery;
import models.resource.TrunkNo;
import models.security.utils.SecurityConstant;
import net.sf.json.JSONObject;
import play.data.binding.ParamNode;
import play.data.validation.Valid;
import play.mvc.After;
/**
 * 企业账户管理
 * @author jinchaoyang
 */
public class Accounts extends BaseController{
    /**
     * 列表
     * @param page
     * @param query
     */
    public static void index(Integer page,AccountQuery query){
        PagerRS<Account> rs = (PagerRS<Account>) Account.findByPager(getQuery(query, AccountQuery.class), getPageNo(page),
                getPageSize());
        render(rs);
    }
    /**
     * 新增
     */
    public static void add(){
        Map<String,String> editData = buildData(1, null, null);
        render(editData);
    }
    /**
     * 创建
     * @param account
     */
    public static void create(@Valid Account account,String[] trunknos){
        if(validation.hasErrors()){
            Map<String,String> editData = buildData(3, null, trunknos);
            saveUserLogAndNotice("创建失败", false);
            render("@add",editData);
        }else{
            String loginerId = SecurityUtil.getLoginUserId();
            account.creatorId = loginerId;
            account.operatorId = loginerId;
            account.save();
            account.bind(trunknos);
            account.createAccount(); //通知proxy发送创建请求
            saveUserLogAndNotice("创建成功", true);
            index(null,null);
        }
    }
    /**
     * 编辑
     * @param id
     */
    public static void edit(String id){
        Account account = Account.findById(id);
        Map<String,String> editData = buildData(2, account, null);
        render(account,editData);
    }
    /**
     * 更新
     * @param id
     */
    public static void update(String id,String[] trunknos){
        Account account = Account.findById(id);
        account.edit(ParamNode.convert(params.all()), "account");
        validation.valid(account);
        if(validation.hasErrors()){
            Map<String,String> editData = buildData(3, account, trunknos);
            saveUserLogAndNotice("更新失败", false);
            render("@edit",account,editData);
        }else{
            String loginerId = SecurityUtil.getLoginUserId();
            account.operatorId = loginerId;
            account.updatedAt = new Date();
            account.save();
            account.rebind(trunknos);
            if(!StringUtil.isBlank(account.appId)){
                account.updateAccount(); //通知proxy更新账户信息
            }else{
                account.createAccount(); //通知proxy创建账户信息
            }
            saveUserLogAndNotice("更新成功", true);
            index(null,null);
        }
    }
    /**
     * 删除
     * @param id
     */
    public static void destroy(String id){
        Account account = Account.findById(id);
        if(null!=account){
            String loginerId = SecurityUtil.getLoginUserId();
            account.operatorId = loginerId;
            account.destroy();
            account.unbind();
            if(!StringUtil.isBlank(account.appId)){
                account.destroyAccount(); //通知proxy删除账户信息
            }
            saveUserLogAndNotice("删除成功", true);
        }else{
            saveUserLogAndNotice("删除失败", false); 
        }
        index(null,null);
    }
    
    /**
     * 数据同步
     */
    public static void sync(String id){
        Account account  = Account.findById(id);
        Map<String,String> result = new HashMap<String,String>();
        if(null!=account){
            if(StringUtil.isBlank(account.appId)){ //创建同步
                result = account.createAccount();
            }else if(0 == account.status){ //删除同步
                result = account.destroyAccount();
            }else{
                result = account.updateAccount();  //更新同步
            }
        }
       JSONObject obj = JSONObject.fromObject(result);
       renderJSON(obj);
    }
    
    
    /**
     * 查看
     * @param id
     */
    public static void show(String id){
        Account account = Account.findById(id);
        render(account);
    }
    
    /**
     * 
     * @param buildType 1:添加  2:修改  3:失败
     * @param account
     * @param trunkNos
     * @return
     */
    private static Map<String,String> buildData(int buildType, Account account, String[] trunkNos){
        Map map = new HashMap();
        Map<String,String> allNos = TrunkNo.queryAllNos();
        Map<String,String> nos = null;
        nos= Account.readyAssignTrunkNos();

        String rid = "";
        if(1 == buildType || 3 == buildType){
            rid = CollectionUtil.join(trunkNos, ",");
        }else{
            rid = CollectionUtil.joinEnitiy(account.getTrunkNos(), null, TrunkNo.class, "id");
        }
        if (!StringUtil.isBlank(rid)) {
            map.put("rids", CollectionUtil.getMapFromKeys(allNos, rid.split(","), String.class));
            nos = CollectionUtil.removeByKeys(nos, rid.split(","), String.class);
        }
        map.put("nos", nos);
        return map;
    }
    
    
    
   
    @After(only = { "accounts.Accounts.create", "accounts.Accounts.update", "accounts.Accounts.destroy" })
    public static void lifeCycle() {
            DicUtil.loadByDicName(AccountConstant.DIC_ACCOUNT_LIST_NAME);
    }
    
}
